package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    public Result<String> save(EmployeeDTO employeeDTO) {
        log.info("当前的线程id:{}", Thread.currentThread().getId());

        Employee employee = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);//源-->目标
        //设置剩下没有拷贝的属性,比如,账号状态,创建时间,创建人
        //设置账号的状态,默认正常状态,1正常,0锁定  引用规范的常用的状态量类,代码规范性,优雅 StatusConstant
        employee.setStatus(StatusConstant.ENABLE);
        //设置密码,默认密码数:123456  但是不能直接存入,需要MD5加密 :DigestUtils.md5DigestAsHex("123456".getBytes())
        //代码规范:PasswordConstant.DEFAULT_PASSWORD 默认密码的常量类  -优雅
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //创建时间,更新时间,创建人,修改人
       // employee.setCreateTime(LocalDateTime.now());//LocalDateTime.now() 本地时间
       // employee.setUpdateTime(LocalDateTime.now());

        //设置当前记录的创建人的id和修改人的id

        //employee.setCreateUser(BaseContext.getCurrentId());
       // employee.setUpdateUser(BaseContext.getCurrentId());

        //持久层
        employeeMapper.insert(employee);
        return Result.success();

    }

    /**
     * 员工分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //分页查询的limit,可以有分页插件PageHandle明捷管理  select * from employee limit 0,10
        //com.github.pagehelper 调用PageHelper的startPage()的方法

        //1.开始分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        //2.根据条件进行查询获取records数据 Page  com.github.pagehelper public class Page<E> extends ArrayList<E>
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

        //为什么1.与2.不能换位置,因为1.是分页查询,2.是查询数据,所以1.是先分页,2.是先查询数据
        //3.将分页查询后的数据封装到PageResult中,其中1.与2.是内置方法ThreadLocal进行联系的
        long total = page.getTotal();
        List<Employee> result = page.getResult();
        return new PageResult(total, result);
    }


    /**
     * 启用禁用员工账号
     *
     * @param status
     * @param id
     */
    public void status(Integer status, long id) {
        //正常: update employee set status =? where id = ?
        //但是为了能够动态且方便的更新数据,可以进行实体类的更新,
        // 下面用的是实体类的Build链式赋值,记得实体类@Build()
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();
        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    public Employee getById(Long id) {
        Employee employee=employeeMapper.getById(id);
        //查询到值了.处理一下返回到前端的密码,减少密码的泄露
        employee.setPassword("****");
        return employee;
    }

    /**
     * 编辑员工信息
     * @param employeeDTO
     */
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);

        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.update(employee);
    }

}
